#include "pch.h"
#include "ExceJs.h"
using namespace Common;
ExceJs::ExceJs(void)
{
}

ExceJs::~ExceJs(void)
{
}


bool ExceJs::CallJScript(const PTCHAR strFunctionName, DISPPARAMS dispParams, VARIANT *varResult, EXCEPINFO *exceptInfo, UINT *nArgErr)
{
	if(pDoc2 == NULL)
		return false;
    IDispatch * pDispScript=NULL;
	HRESULT hResult;

	hResult=pDoc2->get_Script(&pDispScript);

	if(FAILED(hResult))
	{
		return false;
	}
	DISPID dispid;
	CComBSTR objbstrValue=strFunctionName;
	BSTR bstrValue=objbstrValue.Copy();
	OLECHAR *pszFunction=bstrValue;
	hResult=pDispScript->GetIDsOfNames(IID_NULL,&pszFunction,1,LOCALE_SYSTEM_DEFAULT,&dispid);
	if(S_OK!=hResult)
	{
		pDispScript->Release();
		return SUCCEEDED(hResult);
	}

	varResult->vt=VT_VARIANT;
	hResult=pDispScript->Invoke(dispid,IID_NULL,LOCALE_SYSTEM_DEFAULT,DISPATCH_METHOD,&dispParams,varResult,exceptInfo,nArgErr);
	pDispScript->Release();
	pDispScript=NULL;
	return SUCCEEDED(hResult);
}

bool ExceJs::CallJScript(const PTCHAR strFunctionName)
{
	CComVariant varResult;
	CStringArray paramArray;
	return CallJScript(strFunctionName, paramArray, &varResult);
}

bool ExceJs::CallJScript(const PTCHAR strFunctionName,const CStringArray& paramArray)
{
  	CComVariant varResult;
    return CallJScript(strFunctionName,paramArray,&varResult);
}

bool ExceJs::CallJScript(const PTCHAR strFunctionName, const CStringArray &paramArray, VARIANT *varResult)
{
    const INT_PTR arraySize = paramArray.GetSize();
	DISPPARAMS dispparams;
	memset(&dispparams, 0, sizeof dispparams);
	dispparams.cArgs = (UINT)arraySize;
	dispparams.rgvarg = new VARIANT[dispparams.cArgs];

	for( int i = 0; i < arraySize; i++)
	{
		CComBSTR bstr = paramArray.GetAt(arraySize - 1 - i); // back reading
		bstr.CopyTo(&dispparams.rgvarg[i].bstrVal);
		dispparams.rgvarg[i].vt = VT_BSTR;
	}
	dispparams.cNamedArgs = 0;
	EXCEPINFO exceptInfo;
	memset(&exceptInfo, 0, sizeof exceptInfo);
   	//CComVariant varResult;
	UINT nArgErr = (UINT)-1;  // initialize to invalid arg

	return CallJScript(strFunctionName,dispparams,varResult,&exceptInfo,&nArgErr);
}

bool ExceJs::GetJScripts(CComPtr<IHTMLElementCollection>& spColl)
{
	HRESULT hr = pDoc2->get_scripts(&spColl);
	ATLASSERT(SUCCEEDED(hr));
	return SUCCEEDED(hr);
}
